package reflection.class_;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA
 * Description:Class主要方法学习
 * User:22954
 * Date:2024-04-12
 * Time:17:11
 */
public class Methods {
    /*
    public static Class<?> forName(String className)    获得className的反射对象
    public String toString()    获得被反射类的完整路径
    public String getName()     获得被反射类名
    public Package getPackage()     获得被反射类的包名
    Object:  public final native Class<?> getClass()    获得反射对象的类
    public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)    获得被反射类的构造器
    Constructor:  public T newInstance(Object ... initargs)     通过被反射对象的构造器实例化被反射对象
    public Field getDeclaredField(String name)      获得被反射类的属性
    Field:  public Object get(Object obj)       获得实例化对象的Field属性的数据
            public void set(Object obj, Object value)    修改实例化对象的Field属性数据

     */
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> aClass = Class.forName("reflection.Cat");
        System.out.println(aClass.toString());//class reflection.Cat
        System.out.println(aClass.getName());//reflection.Cat
        System.out.println(aClass.getPackage());//package reflection
        System.out.println(aClass.getClass());//class java.lang.Class

        Object o = aClass.getDeclaredConstructor().newInstance();
        System.out.println(o);//Cat{name='null', age=0, step=0, id='null'}

        Field age = aClass.getDeclaredField("age");
        System.out.println(age.get(o));//0
        age.set(o,10);
        System.out.println(age.get(o));//10
        Object o1 = age.get(o);
        System.out.println(o1);//10
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.get(o));//null 10 0 null----不安全,若有不为public的属性则会抛出异常
        }
    }
}
